/**
 * 结合antd form表单、table组件进行数据请求，并返回数据列表的自定义hooks
 */
import { useState,useEffect } from 'react'
// 初始页码 pn:当前页 ps:每页数据条数
const InitPagePination = {
    ps: 10,
    pn: 1,
}
interface ListProps {
    formRef: React.MutableRefObject<any>;
    handleParams?: (params:any) => any;
    request: (params?: any) => Promise<any>;
    initParams?: any;
    extraParams?: any;
}
function useList({ formRef, handleParams = val => val, request, initParams={},extraParams={}}:ListProps){
    const { pn=1, ps=10, ...rst} = initParams;
    const [list,setList] = useState([]);
    const [loading,setLoading] = useState(false);
    const [req,setReq] = useState(0);
    const [params,setParams] = useState({
        ...rst,
        ...extraParams,
    })
    const [pagnation,setPagnation] = useState<any>({
        ...InitPagePination,
        pn,
        ps,
        total:0,
    })
    
    useEffect(() => {
        const initQuery = async () => {
            try {
                setLoading(true);
                const res = await request({ ...params, pn:pagnation.pn, ps:pagnation.ps});
                setList(res?.list || []);
                const pn = res?.pn || pagnation.pn;
                const ps = res?.ps || pagnation.ps;
                // ?? 只有左侧值为null或undefined时才会返回右侧的值
                const total = res?.total ?? pn * ps + 1;
                setPagnation({
                    pn:pn,
                    ps:ps,
                    total:total,
                })
            } finally {
                setLoading(false);
            }
        }
        initQuery();
    },[req])
    
    /**
     * @description 页码修改
     * @param cur 
     * @param pageSize 
     */
    const onChangePination = (cur, pageSize){
        setPagnation({
            ...pagnation,
            pn: cur,
            ps: pageSize,
        })
        onEnforceReq();
    }
    
    const onSearch = () => {
        const curFormParams = formRef?.current?.getFrieldsValue() || {};
        const params = handleParams({...curFormParams,...extraParams});
        setPagnation({
            ...pagnation,
            pn:1,
        })
        setParams(params);
        setReq(req+1);
    }

    const onReset = () => {
        setParams(extraParams);
        setPagnation({
            ...pagnation,
            pn:1,
        })
        setReq(req + 1);
    }

    const onReReq = () => {
        setReq(req + 1);
    }

    const onEnforceReq = () => {
        setReq(req => req + 1);
    }

    return {
        list,
        params,
        loading,
        pn: pagnation?.pn,
        ps: pagnation?.ps,
        total: pagnation?. total,
        onChangePination,
        onSearch,
        onReset,
        onReReq,
        onEnforceReq,
    }
}